package com.gps.skyrc.activity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.gps.skyrc.R;
import com.gps.skyrc.activity.base.BaseActivity;
import com.gps.skyrc.api.Config;
import com.gps.skyrc.api.EventBusCode;
import com.gps.skyrc.bean.DeviceInfo;
import com.gps.skyrc.bean.EventBusMessage;
import com.gps.skyrc.bean.HistoryData;
import com.gps.skyrc.data.ParseData;
import com.gps.skyrc.tool.HexUtil;
import com.gps.skyrc.tool.MyTitleBar;
import com.gps.skyrc.tool.SharedPreferencesUtils;
import com.gps.skyrc.tool.StaticUtils;
import com.gps.skyrc.tool.Tip;
import com.gps.skyrc.tool.logger.ILogger;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;

/**
 * Create by ywq
 * data 2018/11/24
 */
public class TestDetailActivity extends BaseActivity {
    @BindView(R.id.detail_title)
    MyTitleBar mDetailTitle;
    @BindView(R.id.chart_title_ll)
    LinearLayout mChartTitlell;
    @BindView(R.id.chart)
    LineChart mChart;
    @BindView(R.id.item_rl1_body)
    TextView itemRl1Body;
    @BindView(R.id.item_rl2_title)
    TextView itemRl2Title;
    @BindView(R.id.item_rl2_body)
    TextView itemRl2Body;
    @BindView(R.id.item_rl2)
    RelativeLayout itemRl2;
    @BindView(R.id.item_rl3_title)
    TextView itemRl3Title;
    @BindView(R.id.item_rl3_body)
    TextView itemRl3Body;
    @BindView(R.id.item_rl3)
    RelativeLayout itemRl3;
    @BindView(R.id.item_rl4_title)
    TextView itemRl4Title;
    @BindView(R.id.item_rl4_body)
    TextView itemRl4Body;
    @BindView(R.id.item_rl4)
    RelativeLayout itemRl4;
    @BindView(R.id.item_rl5_title)
    TextView itemRl5Title;
    @BindView(R.id.item_rl5_body)
    TextView itemRl5Body;
    @BindView(R.id.item_rl5)
    RelativeLayout itemRl5;
    @BindView(R.id.item_rl6_title)
    TextView itemRl6Title;
    @BindView(R.id.item_rl6_body)
    TextView itemRl6Body;
    @BindView(R.id.item_rl6)
    RelativeLayout itemRl6;
    @BindView(R.id.speed_title_hint)
    TextView speedTitleHint;
    @BindView(R.id.acc_title_hint)
    TextView accTitleHint;

    private int mode = 0;//0默认 1速度  2距离  3赛道  4飞行
    private BleDevice mBleDevice;
    private DeviceInfo mDeviceInfo;
    private String mWhich;
    private HistoryData mHistoryData;
    private int unit = 0;//0默认千米   1英里
    private LineData mLineData;
    private String mLastMac;
    private int mUnit;
    private YAxis mAxisLeft;

    @Override
    protected void getLayout() {
        setContentView(R.layout.activity_test_detail);
    }

    @Override
    protected void setTitleBar() {
        mDetailTitle.initViewsVisible(true, true, false, true, false, true);
        mDetailTitle.setAppTitle(getString(R.string.test_result));
        mDetailTitle.setOnLeftButtonClickListener(v -> onBackPressed());
    }

    @Override
    protected void init() {
        initChart();
        mWhich = getIntent().getStringExtra("which");

        if (mWhich.equals("history")) {
            int isOnOff = getIntent().getIntExtra("isOnOff", 0);//默认不在线
            mHistoryData = getIntent().getParcelableExtra(Config.HISTORY_SINGLE_DATA);
//            if (isOnOff == 1) {
//                mBleDevice = getIntent().getParcelableExtra(Config.BLE_SEND_BLEDEVICE);
//                getFromHistoryData();
//            } else {
            setOffInfo();
//            }
        } else if (mWhich.equals("main")) {//肯定在线
            Tip.showLoadDialog(mContext);
            mDeviceInfo = getIntent().getParcelableExtra("deviceInfo");
            mBleDevice = getIntent().getParcelableExtra(Config.BLE_SEND_BLEDEVICE);
            mHistoryData = new HistoryData();
            getFromMainMsg();
        }
        mLastMac = (String) SharedPreferencesUtils.getParam(mContext, SharedPreferencesUtils.PreKey.LAST_DEVICE_MAC, "");
        mUnit = (int) SharedPreferencesUtils.getParam(mContext, mLastMac, 0);


    }

    //离线时  判断是否保存有详细数据
    private void setOffInfo() {
        //当为直线测试  根据list判断
        //当为赛道飞行  根据用时判断
        if (mHistoryData.getMode() == 0 || mHistoryData.getMode() == 1) {
            if (mHistoryData.getSpeedList().size() > 0)
                toShow(mHistoryData);
            else {
                //无数据
                Tip.showToast(mContext, getString(R.string.no_data));
                setNoData();
            }
        } else if (mHistoryData.getMode() == 2 || mHistoryData.getMode() == 3) {
            if (mHistoryData.getTime() != 0)
                toShow(mHistoryData);
            else {
                //无数据
                Tip.showToast(mContext, getString(R.string.no_data));
                setNoData();
            }
        }
    }

    //没有数据时的界面详情
    private void setNoData() {
        itemRl1Body.setText("——");
        itemRl2Body.setText("——");
        itemRl3Body.setText("——");
        itemRl4Body.setText("——");
        itemRl5Body.setText("——");
        itemRl6Body.setText("——");
        mChart.setVisibility(View.INVISIBLE);
    }

    private void initChart() {
        mChart.getDescription().setEnabled(false);
        mChart.setTouchEnabled(false);
        mChart.setDragDecelerationFrictionCoef(0.8f);
        mChart.setDragEnabled(false);
        mChart.setScaleEnabled(false);
        mChart.setDrawGridBackground(false);
        mChart.setHighlightPerDragEnabled(false);
        mChart.setPinchZoom(false);
        mChart.animateY(2000);

        Legend legend = mChart.getLegend();
        legend.setEnabled(false);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setDrawInside(false);//设置图例是否在图表内部或外部绘制
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    private void getFromHistoryData() {
        //yyyy/MM/dd/HH/mm/ss
        byte[] cmd = {0x0f, 0x05, 0x07, 0, 0, 0, 0, (byte) 0xff, (byte) 0xff};
        int historyDetailId = mHistoryData.getHistoryDetailId();
        cmd[4] = (byte) (historyDetailId & 0xFF);
        int checksum = 1;
        for (int i = 2; i < 6; i++)
            checksum += cmd[i];
        cmd[6] = (byte) (checksum & 0xFF);
        ILogger.d("history_data:" + HexUtil.formatHexString(cmd, true));
        BleManager.getInstance().write(mBleDevice, Config.UUID_SERVICE, Config.UUID_WRITE, cmd, new BleWriteCallback() {
            @Override
            public void onWriteSuccess(int current, int total, byte[] justWrite) {
                Tip.closeLoadDialog();
                ILogger.d("请求成功");
            }

            @Override
            public void onWriteFailure(BleException exception) {
                Tip.closeLoadDialog();
                Tip.showToast(mContext, R.string.send_error);
            }
        });
    }

    //请求数据
    private void getFromMainMsg() {
        int testMode = mDeviceInfo.getTestMode();
        byte[] cmd = {0x0f, 0x04, 0x02, 0, (byte) testMode, 0, (byte) 0xff, (byte) 0xff};
        if (testMode == 0 || testMode == 1)
            cmd[2] = 0x02;
        else if (testMode == 2 || testMode == 3)
            cmd[2] = 0x04;
        int checksum = 1;
        for (int i = 2; i < 5; i++)
            checksum += cmd[i];
        cmd[5] = (byte) (checksum & 0xFF);

        ILogger.d("from main history detail:" + Arrays.toString(cmd));
        BleManager.getInstance().write(mBleDevice, Config.UUID_SERVICE, Config.UUID_WRITE, cmd, new BleWriteCallback() {
            @Override
            public void onWriteSuccess(int current, int total, byte[] justWrite) {
                Tip.closeLoadDialog();
                ILogger.d("请求成功");
            }

            @Override
            public void onWriteFailure(BleException exception) {
                Tip.closeLoadDialog();
                Tip.showToast(mContext, R.string.send_error);
            }
        });
    }

    @SuppressLint("SetTextI18n")
    private void toShow(HistoryData data) {
        int mode = data.getMode();
        if (mode == 4) {
            setNoData();
        } else if (mode == 0) {
            mChartTitlell.setVisibility(View.VISIBLE);
            mChart.setVisibility(View.VISIBLE);
            itemRl1Body.setText(getString(R.string.speed_mode));
            itemRl2Title.setText(getString(R.string.test_speed));
            if (mUnit == 0)
                itemRl2Body.setText(data.getStartSpeed() + "-" + data.getEndSpeed() + getString(R.string.kmh));
            else {//km/h->mi/h  0.62
                itemRl2Body.setText(String.format(Locale.getDefault(), "%.2f", data.getStartSpeed() * 0.62)
                        + "-" + String.format(Locale.getDefault(), "%.2f", data.getEndSpeed() * 0.62) + getString(R.string.mih));
            }
            itemRl3Body.setText(String.format("%02d'%02d''%02d'''", data.getTime() / 60000, data.getTime() % 60000 / 1000, data.getTime() % 60000 % 100));
            itemRl4Title.setText(getString(R.string.acceleration));
            itemRl4Body.setText(Collections.max(data.getAccelerationList()) + "");
            itemRl5.setVisibility(View.GONE);
            itemRl6.setVisibility(View.GONE);
            speedTitleHint.setVisibility(View.GONE);
            showImg(mode, data);
        } else if (mode == 1) {
            mChartTitlell.setVisibility(View.VISIBLE);
            mChart.setVisibility(View.VISIBLE);
            itemRl1Body.setText(getString(R.string.distance_mode));
            itemRl2Title.setText(getString(R.string.test_distance));
            if (mUnit == 0) {
                itemRl2Body.setText(data.getStartDistance() + "-" + data.getEndDistance() + getString(R.string.m));
                itemRl4Body.setText(Collections.max(data.getSpeedList()) + getString(R.string.kmh));
            } else {//m->mi
                itemRl2Body.setText(String.format(Locale.getDefault(), "%.2f", data.getStartDistance() * 0.0006214)
                        + "-" + String.format(Locale.getDefault(), "%.2f", data.getEndDistance() * 0.0006214) + getString(R.string.mi));
                itemRl4Body.setText(String.format(Locale.getDefault(), "%.2f", Collections.max(data.getSpeedList()) * 0.62) +
                        getString(R.string.mih));
            }
            itemRl3Body.setText(String.format("%02d'%02d''%02d'''", data.getTime() / 60000, data.getTime() % 60000 / 1000, data.getTime() % 60000 % 100));
            itemRl4Title.setText(getString(R.string.max_speed));
            itemRl5Title.setText(getString(R.string.acceleration));
            itemRl5Body.setText(Collections.max(data.getAccelerationList()) + "");
            itemRl6.setVisibility(View.GONE);
            showImg(mode, data);
        } else if (mode == 2) {
            mChartTitlell.setVisibility(View.GONE);
            mChart.setVisibility(View.GONE);
            itemRl6.setVisibility(View.GONE);
            itemRl1Body.setText(getString(R.string.track_test));
            itemRl2Title.setText(getString(R.string.distance));
            if (mUnit == 0) {
                itemRl2Body.setText(data.getDistance() + getString(R.string.m));
                itemRl4Body.setText(String.format(Locale.getDefault(), "%.2f", (data.getAverageSpeed() * 1.852)) +
                        getString(R.string.kmh));//海里 转
                itemRl5Body.setText(String.format(Locale.getDefault(), "%.2f", data.getMaxSpeed() * 1.852)
                        + getString(R.string.kmh));
            } else {//转
                itemRl2Body.setText(String.format(Locale.getDefault(), "%.2f", data.getDistance() * 0.0006214)
                        + getString(R.string.mi));
                itemRl4Body.setText(String.format(Locale.getDefault(), "%.2f", (data.getAverageSpeed() * 1.852 * 0.62)) +
                        getString(R.string.mih));//海里 转
                itemRl5Body.setText(String.format(Locale.getDefault(), "%.2f", data.getMaxSpeed() * 1.852 * 0.62)
                        + getString(R.string.kmh));
            }
            itemRl3Body.setText(String.format("%02d'%02d''", data.getTime() / 60, data.getTime() % 60));
            itemRl4Title.setText(getString(R.string.average_speed));
            itemRl5Title.setText(getString(R.string.max_speed));
            itemRl6Title.setText(getString(R.string.slope));
            itemRl6Body.setText(String.format(Locale.getDefault(), "%.2f", data.getSlope()));
        } else if (mode == 3) {
            mChartTitlell.setVisibility(View.GONE);
            mChart.setVisibility(View.GONE);
            itemRl6.setVisibility(View.GONE);
            itemRl1Body.setText(getString(R.string.fly_test));
            itemRl2Title.setText(getString(R.string.distance));
            if (mUnit == 0) {
                itemRl2Body.setText(data.getDistance() + getString(R.string.m));
                itemRl4Body.setText(String.format(Locale.getDefault(), "%.2f", (data.getAverageSpeed() * 1.852)) +
                        getString(R.string.kmh));//海里 转
                itemRl5Body.setText(String.format(Locale.getDefault(), "%.2f", data.getMaxSpeed() * 1.852)
                        + getString(R.string.kmh));
                itemRl6Body.setText(data.getMaxHeight() + getString(R.string.m));
            } else {
                itemRl2Body.setText(String.format(Locale.getDefault(), "%.2f", data.getDistance() * 0.0006214)
                        + getString(R.string.mi));
                itemRl4Body.setText(String.format(Locale.getDefault(), "%.2f", (data.getAverageSpeed() * 1.852 * 0.62)) +
                        getString(R.string.mih));//海里 转
                itemRl5Body.setText(String.format(Locale.getDefault(), "%.2f", data.getMaxSpeed() * 1.852 * 0.62)
                        + getString(R.string.kmh));
                itemRl6Body.setText(String.format(Locale.getDefault(), ".2f", data.getMaxHeight() * 0.0006214) + getString(R.string.mi));
            }
            itemRl4Title.setText(getString(R.string.average_speed));
            itemRl5Title.setText(getString(R.string.max_speed));
            itemRl6Title.setText(getString(R.string.max_height));
            itemRl3Body.setText(String.format("%02d'%02d''", data.getTime() / 60, data.getTime() % 60));
        }
    }

    /**
     * 画图片  添加数据
     */
    private void showImg(int mode, HistoryData data) {
        mAxisLeft = mChart.getAxisLeft();
        mAxisLeft.setTextColor(getResources().getColor(R.color.hdop_orange));
        mAxisLeft.setAxisMaximum(2f);//为此轴设置自定义最大值。 不设置取的是数据的值进行比较
        mAxisLeft.setAxisMinimum(-2f);//为此轴设置自定义最小值。
        mAxisLeft.setDrawGridLines(false);//网格线
        mAxisLeft.setGranularityEnabled(true);//在轴值间隔上启用/禁用粒度控制
        mAxisLeft.setDrawZeroLine(true);
        if (mode == 1) {
            YAxis axisRight = mChart.getAxisRight();
            axisRight.setTextColor(getResources().getColor(R.color.blue_normal));
//            axisRight.setAxisMaximum(1000);
//            axisRight.setAxisMinimum(-1000);
            axisRight.setDrawGridLines(false);//网格线
            axisRight.setDrawZeroLine(false);//零线 中间那条横线
            axisRight.setGranularityEnabled(false);//在轴值间隔上启用/禁用粒度控制
        }
        setData(data);
    }

    /**
     * 设置数据
     */
    private void setData(HistoryData data) {
        ArrayList<Entry> accelerationList = new ArrayList<>();
        for (int i = 0; i < data.getAccelerationList().size(); i++) {
            float val = data.getAccelerationList().get(i);
            accelerationList.add(new Entry(i, val));
        }

        ArrayList<Entry> speedList = new ArrayList<>();
        for (int j = 0; j < data.getSpeedList().size(); j++) {
            float val = data.getSpeedList().get(j);
            speedList.add(new Entry(j, val));
        }

//        int max = Math.round(Collections.max(data.getAccelerationList()));
//        int min = Math.round(Collections.min(data.getAccelerationList()));
//        mAxisLeft.setAxisMaximum(max);
//        mAxisLeft.setAxisMinimum(min);

        LineDataSet setAcc = new LineDataSet(accelerationList, "acceleration");
        setAcc.setAxisDependency(YAxis.AxisDependency.LEFT);
        setAcc.setColor(getResources().getColor(R.color.hdop_orange));
        setAcc.setCircleColor(Color.WHITE);
        setAcc.setLineWidth(2f);//图表的线宽
        setAcc.setCircleRadius(3f);//设置绘制圆的半径
        setAcc.setFillAlpha(65);//填充线的alpha值（透明度）
//        setAcc.setFillColor(ColorTemplate.getHoloBlue());
//        setAcc.setHighLightColor(Color.rgb(244, 117, 117));
        setAcc.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);//贝塞尔曲线
        setAcc.setDrawValues(false);//数据上的文字
        setAcc.setDrawCircles(false);//数据上的点 就是数据的位置
        setAcc.setDrawCircleHole(false);//将其设置为true以允许在每个数据循环中绘制一个孔

        LineDataSet setSpeed = new LineDataSet(speedList, "speed");
        setSpeed.setAxisDependency(YAxis.AxisDependency.RIGHT);
        setSpeed.setColor(getResources().getColor(R.color.blue_normal));
        setSpeed.setCircleColor(Color.WHITE);
        setSpeed.setLineWidth(2f);
        setSpeed.setCircleRadius(3f);
        setSpeed.setFillAlpha(65);
        setSpeed.setFillColor(ColorTemplate.getHoloBlue());
        setSpeed.setHighLightColor(Color.rgb(244, 117, 117));
        setSpeed.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);//贝塞尔曲线
        setSpeed.setDrawValues(false);//数据上的文字
        setSpeed.setDrawCircles(false);//数据上的点 就是数据的位置
        setSpeed.setDrawCircleHole(false);

        if (data.getMode() == 0) {
            mLineData = new LineData(setAcc);

        } else if (data.getMode() == 1) {
            mLineData = new LineData(setAcc, setSpeed);
        }
        mLineData.setValueTextColor(Color.WHITE);
        mLineData.setValueTextSize(9f);
        mChart.setData(mLineData);
    }

    /**
     * 订阅eventbus事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSubEventBus(EventBusMessage message) {
        int code = message.getCode();
        if (code == EventBusCode.EVENT_BUS_READ_DATA) {//解析是一致的
            byte[] data = (byte[]) message.getData();
            HistoryData historyData = ParseData.parseHistoryDetail(data, mHistoryData);
//            historyData.save();
            toShow(historyData);
            ILogger.d("read from main data:" + Arrays.toString(data));
        }
    }
}
